import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

export default {
  data() {
    return {
      stompClient: '',
      reTry: true,
      socketUrl:''
    }
  },
  watch:{
     '$store.state.appVisible'(val){
        console.log("app back to room ",val)
        if(window.terminal.ios && val){
          let _this = this
          _this.reTry = false
          _this.disconnect();
          // 防抖
          if(_this.timer){
            clearTimeout(this.timer)
          }
          _this.timer = setTimeout(()=>{
            _this.reTry = true
            if(!_this.stompClient){
              _this.n = _this.n + 1
              console.log(_this.n, "go to reconnect websocket ------",_this.socketUrl)
              _this.connection(_this.socketUrl)
            }
          },1266)
        }
     }
  },
  methods: {
    initWebSocket(url) {
      if(this.stompClient){
        this.disconnect()
      }
      setTimeout(() => {
        this.socketUrl = url
        this.connection(url)
      }, 0);
    },
    connection(url) {
      let _this = this
      // 建立连接对象
      // let socket = new SockJS('http://127.0.0.1:8286/liveSocket?token=614be4b48a024328a0455fb63a226cc2&plat=web&sid=619');
      let socket = new SockJS(url);
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(socket);
      this.stompClient.debug = (msg) => {
        if (msg.indexOf('CONNECT') != -1) {
          console.log(msg)
        }
      };
      // 定义客户端的认证信息,按需求配置
      let headers = {}
      // 向服务器发起websocket连接
      this.stompClient.connect(headers, (frame) => {
        /*      if(this.$channel=='zgrscc'&&this.zgrsFun){//中国人寿 机构号订阅消息
              	 this.zgrsFun()
              }*/


        if(typeof this.roomNum != "undefined" && this.roomNum != ''){
          this.updateMember && this.updateMember(parseInt(this.roomNum)+1)
        }

        if (this.$route.params.roomid) {
          _this.$store.dispatch("getSocketConnected", true)
          this.stompClient.subscribe('/topic/roomMsg/' + this.$route.params.roomid, (msg) => {
            _this.do(msg)
          }, {});


          if (this.$channel == 'zgrscc' && this.socketZGMS) {
            this.stompClient.subscribe('/topic/zjMsg/' + this.$route.params.roomid, (msg) => {
              let msgInfo = JSON.parse(msg.body);
              if (msgInfo.elems[0].MsgType != 'TIMCustomElem') {
                this.socketZGMS(msg)
              }

            }, {});
          }

        }

        let id = this.$route.params.roomid || this.$route.params.id
        if (id) {
          this.stompClient.subscribe('/user/topic/' + id + '/message', function(msg) {
            _this.do(msg)
          });
        }


        this.socketCallBack && this.socketCallBack()

        /*
               let userSign = frame.headers['user-name']
                console.log('userSign is ',userSign)
               // 点对点消息
               this.stompClient.subscribe('/user/'+userSign+'/msg', (msg) => {
                  console.log('点对点消息广播成功')
                  console.log(msg);  // msg.body存放的是服务端发送给我们的信息
                },headers);

               //群组消息
                this.stompClient.subscribe('/topic/chat', (msg) => {
                  console.log('群组消息广播成功')
                  console.log(msg);  // msg.body存放的是服务端发送给我们的信息
                },headers);

               //发送接收群组消息
               this.stompClient.send("/topic1/chat",
                 headers,
                 JSON.stringify({sender: '',chatType: 'JOIN'}),
               )
        */

      }, (err) => {
        // 连接发生错误时的处理函数
        if (this.reTry) {
          setTimeout(function() {
            _this.connection(url)
          }, 3000);
          console.log('失败', err)
        }
      });
    }, //连接 后台
    do(msg) {
      try {
        let msgInfo = JSON.parse(msg.body)
        // console.log("msgInfo",msgInfo,msgInfo.elems.length)
        if (msgInfo.elems.length > 0) {
          for (var i in msgInfo.elems) {
            let elem = msgInfo.elems[i]
            if (elem.MsgType == 'TIMCustomElem') {
              let cusMsg = JSON.parse(elem.MsgContent.Data);
              // console.log('cusMsg----',cusMsg)
              switch (cusMsg.type) {
                // 倒计时抽奖 "{"activityId":160,"type":"countdown"}"
                case "countdown":
                  console.log("倒计时抽奖",cusMsg.activityId)
                  if(cusMsg.activityId){
                    this.passSocketMsg && this.passSocketMsg(cusMsg);
                  }
                  break;
                // 倒计时开奖 "{"activityId":160,"type":"countdown"}"
                case "countdown_draw":
                  if(cusMsg.activityId){
                    this.passSocketMsg && this.passSocketMsg(cusMsg);
                  }
                  break;
                case "member"://直播间人数
                  this.updateMember(cusMsg.num);
                  break;
                case "startLive"://提前开播
                  this.roomVideoStartLive();
                  console.log("直播状态由预告转变为直播")
                  this.stompClient.send("/live/changeLive",
                    {"token":this.$token},2)
                  break;
                case "checkInPop": //登记信息
                  this.pushBaoMing();
                  break;
                case "closeLive": //正常停播
                  this.stompClient.send("/live/changeLive",
                    {"token":this.$token},
                    16
                  )
                  setTimeout(() => {
                    this.closeLiveMsg && this.closeLiveMsg({'type': 'closeLiveEnd'}); // 正常停播消息
                  }, cusMsg.data)
                  break;
                case "closeLiveIsUrgent": //违规停播
                    this.disconnect()
                    this.closeLiveMsg && this.closeLiveMsg({'type': 'violations'}); // 违规停播
                  break;
                case "room_delete": //直播活动下架（在后台删除）
                    this.roomDelate && this.roomDelate(cusMsg.tip)
                  break;
                case "hdCount"://点赞+留言
                  this.updateHdCount && this.updateHdCount(cusMsg.num);
                  break;
                case "love":
                  this.appendLoveMsg && this.appendLoveMsg({
                    "un": msgInfo.un,
                    "nick": msgInfo.nick,
                    "headImg": msgInfo.headurl,
                    "num": cusMsg.c
                  });
                  this.$EventBus.$emit('triggerFloatIcon', cusMsg.num);
                  break;
                case "gift":
                  this.appendGiftMsg && this.appendGiftMsg({
                    "un": msgInfo.un,
                    "nick": msgInfo.nick,
                    "headImg": msgInfo.headurl,
                    "data": cusMsg.data
                  });
                  break;
                // case "expGoods":
                //   this.appendExpGoods(cusMsg);
                //   break;
                case "expGoodsV2":
                  cusMsg && cusMsg.data && this.appendExpGoods(cusMsg.data);
                  break
                case "lotto":
                  this.getLotterySocketMsg(cusMsg);
                  break;
                case "pmd":
                  this.pmdData(cusMsg);
                  break;
                default:
              }
            } else if (elem.MsgType == 'LIVE_SOCKET_ERROR') {
              if (elem.MsgContent.Data) {
                if (this.$route.params.roomid) {
                  fun.toastMessage(elem.MsgContent.Data)
                } else {
                  if (elem.MsgContent.Data == 'succ') {
                    this.formChildData({
                      "type": "messageSendSuccess"
                    })
                  } else {
                    fun.toastMessage(elem.MsgContent.Data)
                  }
                  //this.socketMsgCallback(elem.MsgContent.Data)
                }
              }
            }
          }
        }
      } catch (e) {
        console.log(e)
      }
    },
    disconnect() {
      if (this.stompClient) {
        this.stompClient.disconnect();
        this.stompClient = null
      }
    }, // 断开连接
  },
  mounted() {
    //this.initWebSocket('/liveSocket/backVideo?token='+this.$token+'&plat='+fun.getPlatform()+'&vid='+this.lookBackId);
  },
  beforeDestroy: function() {
    // 页面离开时断开连接,清除定时器
    this.reTry = false
    this.disconnect();
  }
}
